import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, SearchOutlined,
  PlusSquareOutlined, EditOutlined,MinusSquareOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, DatePicker,Descriptions } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/shipSRM/chlogo.png'
import * as XLSX from 'xlsx';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDD,
  convertISODateTimeToYYYYMMDDHHMMSS
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'

var storage = window.localStorage;
const { Option } = Select;
import Sortable from '../newmes/sortable.js';
import { use_gpd_initcolmun } from './use_cwgl_config.js';
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
import { useLatest } from 'ahooks';
import Loader from '../../UI/loader.js';
import useStore from '../../useStore.js'
import { clearCache,useDidCache,useDidRecover ,dropByCacheKey } from 'react-router-cache-route';


const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

const Gpd_list = () => {
  const history = useHistory();
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [isloading, setisloading] = useState(false)
  const [initSize, setinitSize] = useState() //table宽度大小
  const [ifshow, setifshow] = useState(true)
  const [listdata, setlistdata] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [columnarr, setcolumnarr] = useState(use_gpd_initcolmun)
  const [startDataStr, setStartDataStr] = useState()
  const [endDataStr, setEndtDataStr] = useState()
  const startDataStrref = useLatest(startDataStr)
  const [showYxcs, setShowYxcs] = useState(false)
  const [showSsyxcs, setShowSsyxcs] = useState(false)
  const [yxcsData, setYxcsData] = useState([])
  const [yxcsColumnarr, setYxcsColumnarr] = useState([])
  const endDataStrref = useLatest(endDataStr)
  const [dataExcel, setDataExcel] = useState([]);
  const [dataMxExcel, setDataMxExcel] = useState([]);
  const { nowroute, setnowroute,collapsed,setcollapsed } = useStore();


  useEffect(() => {
    querylist("")
    storage[`Pc_gpd_list${'_' + storage.userid}`] ? setcolumnarr(JSON.parse(storage[`Pc_gpd_list${'_' + storage.userid}`])) : setcolumnarr(columnarr)
    storage[`Pc_gpd_list_initsize${'_' + storage.userid}`] ? setinitSize(storage[`Pc_gpd_list_initsize${'_' + storage.userid}`]) : setinitSize(1)
  }, [])

  useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

  //路由跳转
  const tonormal = (route) => { history.push({ pathname: route }); }

  const querylist = async () => {
    setisloading(true)
    let rtdata = await fetchsync_util("/admin/cwgl/gpd_list", 'POST', { startDataStrref: startDataStrref.current, endDataStrref: endDataStrref.current }, "json")
    //openNotification_util(rtdata.rtmessage)
    rtdata.resultdata.forEach(element => {
      element.create_time = convertISODateTimeToYYYYMMDDHHMMSS(element.create_time)
      element.update_time = convertISODateTimeToYYYYMMDDHHMMSS(element.update_time)
      element.scrq = element.scrq === null ? "" : convertISODateTimeToYYYYMMDD(element.scrq)

    });
    setlistdata(dealnullorundenfined(rtdata.resultdata))
    setselectedRowKeys([])
    setselectedRows([])
    setifshow(false)
    setisloading(false)
  }

  /**
  * 手动查询
  */
  const handleQuery = async () => {
    setcolumnarr(use_gpd_initcolmun)
    querylist()
  }
  /**
   * 新增
   */
  const handleadd = async () => {
    storage.pre_gpd_item = JSON.stringify({ data: {}, type: "add" })
    dropByCacheKey("gpd_form")
    setnowroute({route:"/shipSRM/cwgl/gpd_form",title:"工票单_新增"}) 
  }

  /**
   * 编辑
   */
  const handleEdit = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据编辑!")
    }
    else {
      storage.pre_gpd_item = JSON.stringify({ data: selectedRows[0], type: "edit" })
      dropByCacheKey("gpd_form")
      setnowroute({route:"/shipSRM/cwgl/gpd_form",title:"工票单_编辑"})     }
  }

  const handleRunParameterQuery = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("请选择一条数据编辑!")
      return
    }
    if (startDataStrref.current && endDataStrref.current) {
      setShowYxcs(true)
      let startDataStr = startDataStrref.current
      let endDataStr = endDataStrref.current
      let rtdata = await fetchsync_util("/admin/cwgl/run_parameter_query", 'POST', { startDataStr, endDataStr, selectedRows }, "json")
      console.log(rtdata.resultdata)
      setYxcsData(rtdata.resultdata.rtdata)
      setYxcsColumnarr(rtdata.resultdata.variableNameListStr)
    }
    else {
      openNotification_util("请选择查询时间范围!")
    }

  }

  const handleRealParameterQuery = async () => {
    if (selectedRows.length !== 1) {
      openNotification_util("请选择一条数据编辑!")
      return
    }
    setShowSsyxcs(true)
    let rtdata = await fetchsync_util("/admin/cwgl/real_parameter_query", 'POST', { selectedRows }, "json")
    console.log(rtdata.resultdata)
    setYxcsData(rtdata.resultdata.rtdata)
    setYxcsColumnarr(rtdata.resultdata.variableNameListStr)
  }
  /**
   * 删除
   */
  const handledelete = async () => {
    let rtdata = await fetchsync_util("/admin/cwgl/delete_gpd", 'POST', { selectedRows }, "json")
    rtdata.rtstatus ? querylist() : 1
  }


  /**
   * 导出
   */
  const handleExport = async () => {
    useexcelauto(selectedRows, columnarr, '工票单')
  }

   /**
   * 获取excel数据
   */
   const handleFetch = async (event) => {
    const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();

        reader.onload = (e) => {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          
          // 第一个sheet页
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          var jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          // // 处理日期序列号
          // function excelDateToJSDate(excelDate) {
          //   const epoch = new Date(Date.UTC(1899, 11, 30)); // Excel 中日期从 1899 年 12 月 30 日开始
          //   return new Date(epoch.getTime() + excelDate * 24 * 60 * 60 * 1000);
          // }

          // // 日期序列号在第九列 
          // jsonData.forEach(row => {
          //   const excellhsj = row[9]; // 获取日期序列号
          //   if (typeof excellhsj === 'number') {
          //     const jsDate = excelDateToJSDate(excellhsj);
          //     row[9] = jsDate.toLocaleDateString(); // 转换为本地日期字符串
          //   }
          // })

          // 处理数据的每一行
          var rows = jsonData.slice(1);
          setDataMxExcel(rows);
          console.log(rows,"明细");

          const secondWorkbook = XLSX.read(data, { type: 'array' });

          // 第二个sheet页
          const secondSheetName = secondWorkbook.SheetNames[1];
          const secondWorksheet = secondWorkbook.Sheets[secondSheetName];
          jsonData = XLSX.utils.sheet_to_json(secondWorksheet, { header: 1 });

          // // 处理日期序列号
          // function excelDateToJSDate(excelDate) {
          //   const epoch = new Date(Date.UTC(1899, 11, 30)); // Excel 中日期从 1899 年 12 月 30 日开始
          //   return new Date(epoch.getTime() + excelDate * 24 * 60 * 60 * 1000);
          // }

          // // 日期序列号在第九列 
          // jsonData.forEach(row => {
          //   const excellhsj = row[9]; // 获取日期序列号
          //   if (typeof excellhsj === 'number') {
          //     const jsDate = excelDateToJSDate(excellhsj);
          //     row[9] = jsDate.toLocaleDateString(); // 转换为本地日期字符串
          //   }
          // })

          // 处理数据的每一行
          rows = jsonData.slice(1);
          rows = rows.slice(0,-1)
          setDataExcel(rows);
          console.log(rows,"主表");
        };

        reader.readAsArrayBuffer(file);
  }
  //导入
  const handleImport = async () => {
    let rtdata = await fetchsync_util("/admin/cwgl/gpd_syn", 'POST', { dataExcel, dataMxExcel, storage }, "json")
    rtdata.rtstatus ? querylist() : 1
  }



    return (
      <div style={{    height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
        backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}>
  
  
  
        <div style={styles.kshcontainer}>
          <div style={{
            width: "99vw", height: "", backgroundColor: "white", overflowX: "scroll", margin: "0.5vw",
            paddingLeft: "1vw"
          }}>
  

          <div style={styleobj.linestyleflex}>
            {/* &nbsp;&nbsp;&nbsp;<span style={{ fontSize: "0.7rem", fontWeight: "800" }}>开始时间：</span><DatePicker locale={locale} showTime
              style={{ width: "200px" }} onChange={(e, dateString) => setStartDataStr(dateString)} /> &nbsp; &nbsp;

            <span style={{ fontSize: "0.7rem", fontWeight: "800" }}>结束时间：</span> <DatePicker locale={locale} showTime
              style={{ width: "200px" }} onChange={(e, datestring) => setEndtDataStr(datestring)} />  &nbsp; &nbsp; */}
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}>
              <ReloadOutlined />刷新</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleadd}>
              <PlusSquareOutlined />新 增</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleEdit}>
              <EditOutlined /> 编 辑 </Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handledelete}>
              <MinusSquareOutlined /> 删 除</Button>
            &nbsp;<Button style={{ backgroundColor: "white", color: "#a91f24", fontWeight: "800" }}
              onClick={handleExport}>
              <FileExcelOutlined />导 出</Button>
          </div>

          <IconFont type="setting" style={{ position: 'absolute', right: '2vw', top: '0.5rem', fontSize: "1.5rem" }}
            onClick={e => setIsModalOpen(true)} />
          {ifshow && <Sortable tableColnum={columnarr} handleTableColomn={(data) => { setcolumnarr(data); }}
            storageName={`Pc_gpd_list${'_' + storage.userid}`} open={isModalOpen} handleOpen={(data) => { setIsModalOpen(data); }}
            initSize={initSize} handleInitSize={(data) => { setinitSize(data); storage[`Pc_gpd_list_initsize${'_' + storage.userid}`] = data; }}
          />}

          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>
              <Spin /></div>)
            :
            (<Custom_table_hooks_config tabledata={listdata} tablecolnum={columnarr}
              width={collapsed?"94%":"84%"}
              sfdoubleclick="false" ifhiddencchangeselecttype="true"
              selectedRows={selectedRows} selectedRowKeys={selectedRowKeys}
              
              defaultPageSize={10}
              bordered
              scroll={{ y: 'calc(100vh - 280px)', x: initSize * 950 }}
              handleselectson={(selectedRows, selectedRowKeys) => {
                setselectedRows(selectedRows)
                setselectedRowKeys(selectedRowKeys)
              }}
            />)
          }
        </div>

      </div>
    </div>
  )
}


export default Gpd_list

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `#F1F1F1`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: { paddingLeft:"1.5vw",paddingRight:"1.5vw", height: "2vw", position: "absolute", right: "8%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },

kshcontainer: {
  width: "100%", minHeight: "40vh", position: "absolute", top: "2vh", left: "0vw", backgroundColor: "#F1F1F1",
  color: "black"
},
}
var styleobj = {
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  linestylesmall: { height: "1.3rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },

  linestyleflex: {
    height: "1.8rem", fontSize: "0.6rem", position: "relative", width: "96vw", marginLeft: "0.1%",
    display: "flex", justifyContent: "flex-start", alignItems: "center", marginBottom: "0.5rem",marginTop:"0.5rem"
  },
  linestyleflexitem: {
    height: "1.6rem", fontSize: "0.7rem", position: "relative", width: "23%", textIndent: "0.5rem",
    backgroundColor: "white", lineHeight: "1.6rem", fontSize: "0.75rem", fontWeight: "500", textAlign: "center"
  },
  linestyleflexitemleft: { backgroundColor: "#F0F0F0", position: "absolute", width: "35%", left: "0" },
  linestyleflexitemright: { backgroundColor: "white", position: "absolute", width: "64%", right: "0" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}